import Decimal from "decimal.js"

/**
 * @description {Function} useEnumeratePicker 根据接口枚举匹配出中文名称
 * @param {any[]} enumList 接口枚举
 * @param {string | number} field 枚举值
 * @param {string} [key] 指定 key 键
 * @param {string} [value] 指定 value 键
 * @author 花东红
 * @time 2024/11/22
 */
export const useEnumeratePicker = (
    enumList: any[],
    field: string | number,
    key?: string,
    value?: string
) => {
    if (!enumList) return
    const matchItem =
        enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
    return matchItem[key ?? 'label'] || ''
}

/**
 * @description {Function} formatDateParams 处理日期参数
 * @param {utilTypes.formatDateParams} data
 * @author 花东红
 * @time 2024/7/15
 */
export const formatDateParams = (data: utilTypes.formatDateParams) => {
    if (!Object.keys(data.params).length) return {}
    const paramsObj = JSON.parse(JSON.stringify(data.params))
    delete paramsObj[data.labelName]
    if (data.params[data.labelName] && data.params[data.labelName].length) {
        return {
            [data.startTimeName ?? 'startTime']: data.params[data.labelName][0].format('YYYY-MM-DD 00:00:00'),
            [data.endTimeName ?? 'endTime']: data.params[data.labelName][1].format('YYYY-MM-DD 23:59:59'),
            ...paramsObj
        }
    }

    return {
        ...data.initialValue,
        ...paramsObj
    }
}
/**
 * @description {Function} filterParams 过滤请求参数
 * @param {utilTypes.filterParams} data
 * @author 花东红
 * @time 2024/7/15
 */
export const filterParams = (data: utilTypes.filterParams): Record<string, any> => {
    if (!Object.keys(data).length) return {}
    return Object.entries(data).reduce((acc, [key, value]) => {
        if (value !== null && value !== undefined && value !== '') {
            acc[key] = value;
        }
        return acc;
    }, {});
}
/**
 * @description 截取url问号后的参数
 */
export const getUrlWithParams = () => {
    const url = {
        hash: location.hash.substring(1),
        history: location.pathname + location.search
    };
    return url['hash'];
}
/**
 * @description 动态设置css属性
 * @param key css属性名
 * @param val css属性值
 */
export const setStyleProperty = (key: string, val: string) => {
    document.documentElement.style.setProperty(key, val);
}

/**
 * @description 验证是否为blob格式
 * @param data 传入Content-Type
 */
export function blobValidate(data: { type: string }) {
    return data.type !== 'application/json'
}

/**
 * @description 获取assets静态资源
 * @param url 传入相对路径
 */
export const getAssetsFile = (url: string) => {
    return new URL(`@/assets/${url}`, import.meta.url).href
}
/**
 * @description 千分位自动补逗号
 * @param num 传入需转换的数据
 */
export const formatNumber = (num: string | number) => {
    if (!num) return
    return num.toString().replace(/\d+/, function (n) {
        return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    })
}

/**
 * @description 截取字符串指定项后面的内容
 * @param str 传入的字符串
 * @param key 截取关键字
 */
export const getCaption = (str: any, key: string) => {
    const index = str.lastIndexOf(key)
    return str.substring(index + 1, str.length)
}

/**
 * @description 一维数组求和
 * @param {Array} arr 传入一维数组，示例arr:[{num:1},{num:2}]
 * @param key 传入对象中需要相加的key参数,key:num
 * @param precision 小数位数
 */
export const sum = (arr: any[], key: string, precision: number = 2) => {
    return arr.reduce(function (total, value) {
        return new Decimal(total).add(new Decimal(value[key])).toFixed(precision)
    }, 0)
}

/**
 * @description 一维数组求和
 * @param {Array} arr 传入需要求和的数组，示例：[1,2,3,4,5]
 */
export const sumItem = (arr: any[]) => {
    return arr.reduce((total, value) => new Decimal(total).add(new Decimal(value)).toString(), 0)
}

/**
 * @description 获取当前时间对应的提示语
 * @returns {String}
 */
export const getTimeState = (): string | undefined => {
    const timeNow = new Date();
    const hours = timeNow.getHours();
    if (hours >= 6 && hours <= 10) return `早上好 ⛅`;
    if (hours >= 10 && hours <= 14) return `中午好 🌞`;
    if (hours >= 14 && hours <= 18) return `下午好 🌞`;
    if (hours >= 18 && hours <= 24) return `晚上好 🌛`;
    if (hours >= 0 && hours <= 6) return `凌晨好 🌛`;
}

/**
 * @description 判断数据类型
 * @param {*} val 需要判断类型的数据
 * @returns {String}
 */
export const isType = (val: any): string => {
    if (val === null) return "null";
    if (typeof val !== "object") return typeof val;
    else return Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase();
}

/**
 * @description 生成唯一 uuid
 * @returns {String}
 */
export const generateUUID = (): string | undefined => {
    let uuid = "";
    for (let i = 0; i < 32; i++) {
        const random = (Math.random() * 16) | 0;
        if (i === 8 || i === 12 || i === 16 || i === 20) uuid += "-";
        uuid += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
    }
    return uuid;
}

/**
 * 判断两个对象是否相同
 * @param {Object} a 要比较的对象一
 * @param {Object} b 要比较的对象二
 * @returns {Boolean} 相同返回 true，反之 false
 */
export const isObjectValueEqual = (a: { [key: string]: any }, b: { [key: string]: any }): boolean => {
    if (!a || !b) return false;
    const aProps = Object.getOwnPropertyNames(a);
    const bProps = Object.getOwnPropertyNames(b);
    if (aProps.length != bProps.length) return false;
    for (let i = 0; i < aProps.length; i++) {
        const propName = aProps[i];
        const propA = a[propName];
        const propB = b[propName];
        if (!Object.prototype.hasOwnProperty.call(b, propName)) return false;
        if (propA instanceof Object) {
            if (!isObjectValueEqual(propA, propB)) return false;
        } else if (propA !== propB) {
            return false;
        }
    }
    return true;
}

/**
 * @description 生成随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @returns {Number}
 */
export const randomNum = (min: number, max: number): number => {
    return Math.floor(Math.random() * (min - max) + max);
}
/**
 * @description 存localStorage
 * @param key 属性名
 * @param params 属性值
 */
export const setLocal = (key: string, params?: any): void => {
    localStorage.setItem(key, params)
}
/**
 * @description 移除localStorage
 * @param key 属性名
 */
export const removeLocal = (key: string): void => {
    localStorage.removeItem(key)
}
/**
 * @description 清空localStorage
 */
export const clearLocal = (): void => {
    localStorage.clear()
}
/**
 * @description 取值localStorage
 * @param key 属性名
 */
export const getLocal = (key: string) => {
    return localStorage.getItem(`${key}`)
}

/**
 * @description 参数转formData
 * @param params 请求参数
 */
export function tansParams(params: { [x: string]: any }) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        const part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        const params = propName + '[' + key + ']';
                        const subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

/**
 * @description {Function} errorCode 网络错误状态码
 * @author 花东红
 * @time 2024/11/22
 */
export const errorCode: Record<string, string> = {
    '401': '当前身份已过期，请重新登录更新状态',
    '403': '暂无',
    '404': '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
}
